<!DOCTYPE html>
<html>

<head>
    <title>个人中心</title>
    <meta charset="utf-8">
    <style>
        html,
        body {
            height: 100%;
            background-color: #66ccff;
        }

        .show {
            display: flex;
            justify-content: center;
            min-height: 100%;
        }

        .box {
            background-color: white;
            margin-top: 50px;
            margin-bottom: 80px;
            width: 1000px;
            height: 600px;
        }

        #charts {
            width: 1000px;
            height: 450px;
        }
    </style>
    <link rel="stylesheet" href="../layui/css/layui.css">
    <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>
    <script src="../layui/layui.js" type="text/javascript"></script>
    <script src="../jquery-3.6.0.min.js" type="text/javascript"></script>
    <script src="../sha1.min.js" type="text/javascript"></script>
    <script>
        window.onload = function () {
            $.ajax({
                url: "manage/check.php",
                type: "GET",
                success(res) {
                    $("#username").val(res);
                }
            })
        }

        // 为Date添加格式化时间方法
        Date.prototype.format = function (fmt) {
            var o = {
                "M+": this.getMonth() + 1,                 //月份 
                "d+": this.getDate(),                    //日 
                "h+": this.getHours(),                   //小时 
                "m+": this.getMinutes(),                 //分 
                "s+": this.getSeconds(),                 //秒 
                "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
                "S": this.getMilliseconds()             //毫秒 
            };
            if (/(y+)/.test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            }
            for (var k in o) {
                if (new RegExp("(" + k + ")").test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                }
            }
            return fmt;
        }

        function exit() {
            $.ajax({
                url: 'deleteSession.php',
                success(res) {
                    window.location.replace("login.html");
                }
            })
        }
    </script>
</head>

<body>
    <div class="show">
        <div class="box" id="personalCenter">
            <div class="layui-tab layui-tab-brief">
                <ul class="layui-tab-title">
                    <li class="layui-this">我的打字信息</li>
                    <li>账号管理</li>
                    <li onclick="window.location.href = '../type/exercise.html'">练习模式</li>
                    <li>竞赛模式</li>
                    <li onclick="window.location.href = '../gameInfo/game.html'">查看竞赛</li>
                </ul>
                <div class="layui-tab-content">
                    <div class="layui-tab-item layui-show">
                        <div name="page1" style="margin-top: 20px;" class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">日期范围</label>
                                <div class="layui-inline" id="range">
                                    <div class="layui-input-inline">
                                        <input type="text" id="startDate" class="layui-input" placeholder="开始日期">
                                    </div>
                                    <div class="layui-form-mid">-</div>
                                    <div class="layui-input-inline">
                                        <input type="text" id="endDate" class="layui-input" placeholder="结束日期">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div name="page1" id="charts"></div>
                    </div>
                    <div class="layui-tab-item">
                        <form class="layui-form" id="change-password" action="changePassword.php" method="post">
                            <div class="layui-form-item">
                                <label class="layui-form-label">用户名</label>
                                <div class="layui-input-inline">
                                    <input type="text" id="username" class="layui-input" disabled>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">修改密码</label>
                                <div class="layui-input-inline">
                                    <input type="password" name="password" required lay-verify="password"
                                        placeholder="请输入新密码" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label"></label>
                                <div class="layui-input-inline">
                                    <input type="password" name="password2" required lay-verify="password2"
                                        placeholder="请再次输入密码" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <button class="layui-btn" lay-submit lay-filter="*">保存</button>
                                    <button type="reset" class="layui-btn layui-btn-primary"
                                        onclick="exit()">退出登录</button>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="layui-tab-item"></div>
                    <div class="layui-tab-item">
                        <form class="layui-form" action="query.php">
                            <div class="layui-form-item">
                                <label class="layui-form-label">邀请码</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="id" required lay-verify="required|number"
                                        placeholder="请输入邀请码" autocomplete="off" class="layui-input" maxlength="6">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <button class="layui-btn" lay-submit>确定</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <footer style="background:none;bottom: 0;width: 100%;height: 50px;margin-top: -50px;text-align: center;">
        <a href="https://github.com/HuanLing4763/dazi/" target="_blank">项目源码</a>
        |
        <a href="mailto:2043417914@qq.com" onclick="window.open('https://gitee.com/huan_ling/dazi/')">联系我们</a>
        <br>
        <a href="https://beian.miit.gov.cn/" target="_blank">湘ICP备20****87号-1</a>
    </footer>
    <script>
        layui.use('form', function () {
            var form = layui.form;

            form.verify({
                password: [
                    /^[a-zA-Z]\w{5,17}$/
                    , '密码必须以字母开头，长度在6~18之间，只能包含字母、数字和下划线'
                ],
                password2: function (value, item) {
                    if ($('input[name=password]').val() != $('input[name=password2').val()) {
                        return '两次输入的密码不一致！'
                    }
                }
            })

            form.on('submit(*)', function (data) {
                let password = sha1(data.field['password']);
                $.ajax({
                    url: "changePassword.php",
                    type: "POST",
                    data: {
                        password: password
                    },
                    success(res) {
                        alert("修改成功！");
                        location.reload();
                    }
                })
                return false;
            })
        })

        var param;
        var chandeParam;

        // 获取数据
        $.ajax({
            url: "getChartsData.php",
            type: "GET",
            dataType: "json",
            success(res) {
                param = eval("(" + res + ")");
                chandeParam = param;
                changeDate(new Date($("#startDate").val()), new Date($("#endDate").val()));
                getCharts();
            }
        })

        /**
         * @method
         * @author  gedesiwen
         * @param {array} arr 需要查找的数组
         * @param {number} num 目标数值，查找的是与这个数值最接近的
         * @param {number} site 值为0或1,0从左找，1从右找
         * @return {number} 返回查找到的最接近的数值的索引
         * @desc 获取数组中与目标数值最接近的数值
         */
        function findCloseNum(arr, num, site) {
            if (site == 0) {
                let index = 0; // 保存最接近数值在数组中的索引
                let d_value = Number.MAX_VALUE; // 保存差值，默认为最大数值
                for (let i = 0; i < arr.length; i++) {
                    let new_d_value = arr[i] - num; // 新差值
                    if (new_d_value <= d_value || d_value < 0) { // 如果新差值小于等于旧差值，保存新差值和索引，如果旧差值小于0，也保存新差值的索引
                        if (new_d_value === d_value) { // 如果数组中两个数值跟目标数值差值一样，取小
                            continue;
                        }
                        index = i;
                        d_value = new_d_value;
                    }
                }
                return index; // 返回最接近的数值的索引
            } else if (site == 1) {
                let index = arr.length - 1;
                let d_value = -Number.MAX_VALUE; // 保存差值，默认为最小数值
                for (let i = 0; i < arr.length; i++) {
                    let new_d_value = arr[i] - num; // 新差值
                    if (new_d_value >= d_value && new_d_value <= 0) { // 如果新差值大于等于旧差值且小于等于0，保存新差值和索引
                        if (new_d_value === d_value && arr[i] < arr[index]) { // 如果数组中两个数值跟目标数值差值一样，取大
                            continue;
                        }
                        index = i;
                        d_value = new_d_value;
                    }
                }
                return index;
            }
        }

        /**
         * 将日期数组转换为时间戳数组
         * @param {array} arr 需要转换的日期数组
         * @return {array} 返回转换后的数组
         */
        function getTimestampArray(arr) {
            var newArr = [];
            for (let i = 0; i < arr.length; i++) {
                let date = new Date(arr[i]);
                let time = date.getTime();
                newArr.push(time);
            }
            return newArr;
        }

        function changeDate(newStartDate, newEndDate) {
            if (!param) return;
            var temp = JSON.parse(JSON.stringify(param));

            var timestampArray = getTimestampArray(param.date);
            var newStartTimestamp = newStartDate.getTime();
            var newEndTimestamp = newEndDate.getTime();

            if (timestampArray[0] > newEndTimestamp || timestampArray[timestampArray.length - 1] < newStartTimestamp) {
                chandeParam.date = null;
                chandeParam.speed = null;
                chandeParam.accuracy = null;
            } else {
                let newStartIndex = findCloseNum(timestampArray, newStartTimestamp, 0);
                let newEndIndex = findCloseNum(timestampArray, newEndTimestamp, 1);

                chandeParam.date = temp.date.slice(newStartIndex, newEndIndex + 1);
                chandeParam.speed = temp.speed.slice(newStartIndex, newEndIndex + 1);
                chandeParam.accuracy = temp.accuracy.slice(newStartIndex, newEndIndex + 1);
            }

            // 重新渲染图表
            getCharts();
        }

        function getCharts() {
            var myChart = echarts.init(document.getElementById("charts"));

            // 指定图表的配置项和数据
            var option = {
                title: {
                    text: '打字速度',
                    left: 'center'
                },
                tooltip: {},
                legend: {
                    data: ['速度', '正确率'],
                    top: 'bottom'
                },
                xAxis: {
                    data: chandeParam.date
                },
                yAxis: [{
                    axisLabel: {
                        formatter: '{value}字/分'
                    }
                },
                {
                    axisTick: {
                        show: false // 不显示坐标轴刻度线
                    },
                    splitLine: {
                        show: false // 不显示网格线
                    },
                    axisLabel: {
                        formatter: '{value}%'
                    }
                }],
                series: [{
                    name: '速度',
                    type: 'line',
                    yAxisIndex: 0,
                    data: chandeParam.speed
                },
                {
                    name: '正确率',
                    type: 'line',
                    yAxisIndex: 1,
                    data: chandeParam.accuracy
                }]
            };

            // 使用刚指定的配置项和数据显示图表。
            myChart.setOption(option);
        }

        layui.use('laydate', function () {
            let laydate = layui.laydate;

            let date = new Date();
            let startDate = new Date(date.getTime() - 7 * 24 * 60 * 60 * 1000);
            let endDate = new Date(date.getTime());
            startDate = startDate.format("yyyy-MM-dd");
            endDate = endDate.format("yyyy-MM-dd");

            laydate.render({
                elem: "#range",
                type: "date",
                value: `${startDate} - ${endDate}`,
                range: ["#startDate", "#endDate"],
                change: function (value, date, endDate) {
                    console.log(value);
                    let newDate = value.split(" - ");
                    let start = new Date(newDate[0]);
                    let end = new Date(newDate[1]);
                    changeDate(start, end);
                }
            })
        })
    </script>
</body>

</html>